package org.arch_learn.netty_rpc.consumer.netty_client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.arch_learn.netty_rpc.consumer.handler.NettyRpcClientHandler;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * 1.连接Netty服务端
 * 2.提供给调用者主动关闭资源的方法
 * 3.提供消息发送的方法
 */
public class NettyRpcClient {
    private String ip;
    private Integer port;

    private NioEventLoopGroup group;

    private Channel channel;

    private NettyRpcClientHandler nettyRpcClientHandler;

    private ExecutorService executorService = Executors.newCachedThreadPool();

    public NettyRpcClient(String ip, Integer port) {
        this.ip = ip;
        this.port = port;
    }

    public void initClient(NettyRpcClientHandler nettyRpcClientHandler) {
        this.nettyRpcClientHandler = nettyRpcClientHandler;
        try {
            //1.设置线程组
            group = new NioEventLoopGroup();
            //2.创建启动助手
            Bootstrap bootstrap = new Bootstrap();
            //3.设置参数
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast(new StringDecoder());
                            pipeline.addLast(new StringEncoder());
                            //添加客户端处理类
                            pipeline.addLast(nettyRpcClientHandler);
                        }
                    });
            //4.连接netty服务端
            channel = bootstrap.connect(ip, port).sync().channel();
        } catch (Exception e) {
            e.printStackTrace();
            if (group != null) {
                group.shutdownGracefully();
            }
            if (channel != null) {
                channel.close();
            }
        }

    }

    public void close() {
        if (group != null) {
            group.shutdownGracefully();
        }
        if (channel != null) {
            channel.close();
        }
    }

    public Object send(String msg) throws ExecutionException, InterruptedException {
        nettyRpcClientHandler.setRequestMsg(msg);
        Future future = executorService.submit(nettyRpcClientHandler);
        return future.get();
    }
}
